﻿using AutoMapper;
using SheepStorage.Domain.Dto.InputDto;
using SheepStorage.Domain.Dto.Output;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Repository.BaseImp;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class SheepPurchaseService:ISheepPurchaseService
    {
        private readonly IBaseRepository<SheepPurchase> _purchaseRepository;
        private readonly IBaseRepository<SheepRecord> _recordRepository;
        private readonly IBaseRepository<EarTagTable> _earRepository;
        private readonly IMapper _mapper;

        public SheepPurchaseService(IBaseRepository<SheepPurchase> purchaseRepository, IBaseRepository<SheepRecord> recordRepository,IMapper mapper, IBaseRepository<EarTagTable> earRepository)
        {
            _purchaseRepository = purchaseRepository;
            _recordRepository = recordRepository;
            _mapper = mapper;
            _earRepository = earRepository;
        }

        /// <summary>
        /// 羊只采购列表
        /// </summary>
        /// <returns></returns>
        public async Task<PageOutput<SheepPurchase>> GetSheepPurchase(SheepPurchaseInput input)
        {
            
            var list =_purchaseRepository.GetAll().Where(c => c.IsDel == 0).ToList();

            if (!string.IsNullOrEmpty(input.PurchaseStartDate))
            {
                list = list.Where(c => c.PurchaseDate >= Convert.ToDateTime(input.PurchaseStartDate)).ToList();
            }
            if (!string.IsNullOrEmpty(input.PurchaseEndDate))
            {
                list = list.Where(c => c.PurchaseDate < Convert.ToDateTime(input.PurchaseEndDate).AddDays(1)).ToList();
            }

            if (input.SheepType!=0)
            {
                list = list.Where(c => c.PurchaseSheepType == input.SheepType).ToList();
            }
            if (!string.IsNullOrEmpty(input.WareHouse))
            {
                list = list.Where(c => c.WareHouse == input.WareHouse).ToList();
            }
            if (input.BuildingManagementId != 0)
            {
                list = list.Where(c => c.BuildingManagementId == input.BuildingManagementId).ToList();
            }
            if (!string.IsNullOrEmpty(input.OverBit))
            {
                list = list.Where(c => c.OverBit == input.OverBit).ToList();
            }
            if (!string.IsNullOrEmpty(input.PurchaseBuyer))
            {
                list = list.Where(c => c.PurchaseBuyer.Contains(input.PurchaseBuyer)).ToList();
            }
            if (!string.IsNullOrEmpty(input.DocumentNumber))
            {
                list = list.Where(c => c.DocumentNumber == input.DocumentNumber).ToList();
            }
            if (input.ProviderId != 0)
            {
                list = list.Where(c => c.ProviderId == input.ProviderId).ToList();
            }
            

            var result = new PageOutput<SheepPurchase>()
            {
                Total = list.Count(),
                PageSize = input.PageSize,
            };

            var entity = list.OrderByDescending(c => c.PurchaseId).Skip(input.PageSize * (input.PageIndex - 1)).Take(input.PageSize).ToList();


            result.Data = entity;

            return result;
        }



        /// <summary>
        /// 羊只采购添加
        /// </summary>
        /// <param name="purchase"></param>
        /// <returns></returns>
        public async Task<int> SheepPurchaseAdd(List<SheepPurchase> PurchaseList)
        {
            using (var tran=new TransactionScope())
            {
                try
                {
                    foreach(var purchase in PurchaseList)
                    {
                        var list = _earRepository.GetAll().FirstOrDefault(c => c.OverBit == purchase.OverBit);
                        list.UseState = 2;
                        _earRepository.Update(list);

                        var sheepPurchase = new SheepPurchase()
                        {
                            PurchaseBuyer = purchase.PurchaseBuyer,
                            PurchaseDate = purchase.PurchaseDate,
                            PurchaseSheepType = purchase.PurchaseSheepType,
                            PurchaseCategory = purchase.PurchaseCategory,
                            PurchaseAccountingUnit = purchase.PurchaseAccountingUnit,
                            ProviderId = purchase.ProviderId,
                            WareHouse = purchase.WareHouse,
                            OverBit = purchase.OverBit,
                            BuildingManagementId = purchase.BuildingManagementId,
                            ColumnId = purchase.ColumnId,
                            PurchaseGender = purchase.PurchaseGender,
                            PurchaseStage = purchase.PurchaseStage,
                            PurchaseGoodsName = purchase.PurchaseGoodsName,
                            PurchaseStandardPackage = purchase.PurchaseStandardPackage,
                            PurchaseMeasure = purchase.PurchaseMeasure,
                            PurchaseAmount = purchase.PurchaseAmount,
                            PurchaseOnlyEvenly = purchase.PurchaseOnlyEvenly,
                            PurchaseMoney = purchase.PurchaseMoney,
                            PurchaseDiscount = purchase.PurchaseDiscount,
                            PurchaseAdjustAmount = purchase.PurchaseAdjustAmount,
                            PurchaseSettlementAmount = purchase.PurchaseSettlementAmount,
                            PurchaseTotalWeight = purchase.PurchaseTotalWeight,
                            PurchaseRemark = purchase.PurchaseRemark,
                            PurchaseSerialNumber = YitIdHelper.NextId().ToString(),
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            BuildingName = purchase.BuildingName,
                            ColumnsName = purchase.ColumnsName,
                            IsDel = 0
                        };
                        _purchaseRepository.Add(sheepPurchase);

                        var sheepRecord = new SheepRecord()
                        {
                            OverBit = purchase.OverBit,
                            ElEarTag = purchase.OverBit,
                            SheepRecordSex = purchase.PurchaseGender,
                            BuildingName = purchase.BuildingManagementId.ToString(),
                            SheepFieldName = purchase.ColumnId.ToString(),
                            SheepRecordType = purchase.PurchaseSheepType,
                            IsDel = false
                        };

                        _recordRepository.Add(sheepRecord);
                    }

                    tran.Complete();
                    return 1;
                }
                catch (Exception ex)
                {
                    
                    throw;
                }
            }
        }



        /// <summary>
        /// 批量删除/逻辑删除
        /// </summary>
        /// <param name="idList"></param>
        /// <returns></returns>
        public async Task<int> DeleteSheepPurchase(params int[] idList)
        {
            if (idList.Length == 0)
            {
                return 0;
            }

            var result = _purchaseRepository.GetAll().Where(c => idList.Contains(c.PurchaseId)).ToList();
            foreach(var item in result)
            {
                item.IsDel = 1;
                item.DelTime = DateTime.Now;
            }

            return _purchaseRepository.UpdateRange(result);


        }


        /// <summary>
        /// 获取羊只采购单条数据
        /// </summary>
        /// <param name="purchaseId"></param>
        /// <returns></returns>
        public async Task<SheepPurchase> GetSheepPurchaseInfo(int purchaseId)
        {
            var list = _purchaseRepository.GetInfoBy(purchaseId);

            return list;
        }


        /// <summary>
        /// 修改羊只采购信息
        /// </summary>
        /// <param name="purchase"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepPurchase(SheepPurchase purchase)
        {
            purchase.PurchaseStandardPackage = "招标中";
            purchase.PurchaseMeasure = "千克";
            purchase.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
            purchase.DocumentNumber=YitIdHelper.NextId().ToString();
            purchase.IsDel = 0;
            purchase.PurchaseAdjustAmount = purchase.PurchaseSettlementAmount;
            var result=_purchaseRepository.Update(purchase);
            purchase.UpdateTime = DateTime.Now;
            return result;
        }



    }
}
